<template>
  <div class="w-p100">
    <div class="chart-container box box-ac box-jc bg-img1">
      <div @click="seeBudgetDetail()" class="chart-text box box-jc box-ac box-ver">
        <div class="text-small">剩余报销总额</div>
        <div class="text-big">&nbsp;{{budget.decAvailable}}&nbsp;</div>
        <!-- <div class="text-small" >已使用{{budget.available}}</div> -->
      </div>
      <div ref="chart" class="chart"></div>
    </div>
    <div v-if="budget.list.length > 0" class="box budget-list">
      <div @click="selectInvoice(item)" v-if="budget.list.length > 1" v-for="(item, index) in budget.list" :style="{'background': item.color}" :value="item" :key="index" class="item box-f1 box box-ac box-jc box-ver">
        <div class="box box-ac">
          <img :src="item.icon" class="icon-budget-small">
          <div class="text">{{item.name}}</div>
        </div>
        <div class="value">{{item.value | formatMoney}}</div>
      </div>
      <div @click="selectInvoice(item)" v-if="budget.list.length == 1" v-for="(item, index) in budget.list" :style="{'background': item.color}" :value="item" :key="index" class="item box-f1 box box-ac box-jc">
        <img :src="item.icon" class="icon-budget-big">
        <div class="box box-ver">
          <div class="text">{{item.name}}</div>
          <div class="value">{{item.value | formatMoney}}</div>
        </div>
      </div>
    </div>
    <div class="travel model">
      <div class="box box-ac head">
        <div class="left"></div>
        <div class="text box-f1">我的行程计划</div>
        <div @click="xinCenList()">全部行程</div>
      </div>
      <div v-if="travelList.length === 0" class="travel-empty box box-ver box-ac box-jc">
        <img class="icon-travel-empty" :src="travelEmpty"/>
        <div>小主，暂无待出差行程哟~</div>
      </div>
      <div :class="{'type1': travelList.length === 1}" class="travel-list box of-x-s">
        <div class="box">
          <div @click="travelbilldetail(item)" v-for="(item, index) in travelList" :value="item" :key="index" class="bill-item">
            <div class="time box">
              <div class="box-f1 tx-c">{{item.startDate}}</div>
              <div class="box-f1 tx-c">{{item.endDate}}</div>
            </div>
            <div class="area box">
              <div class="from tx-c ell box-f1">{{item.from}}</div>
              <div class="icon-index-arrow icon"></div>
              <div class="to tx-c ell box-f1">{{item.to}}</div>
            </div>
            <div class="cause ell">
              {{item.cause}}
            </div>
            <div class="user box box-ac ell" v-html="item.travelPersonShow">
              <!-- <div v-for="(name1, index1) in item.travelPerson.slice(0, 2)" :key="index1" :value="name1" class="item ell box box-ac box-jc">{{name1}}</div>
              <div v-if="item.travelPerson.length > 2">&nbsp;&nbsp;......</div> -->
            </div>
          </div>
          <div @click="addXinCen()" v-if="travelList.length > 1" class="btn-add box box-ac box-jc">
            <div class="icon icon-index-add"></div>
          </div>
          <div @click="addXinCen()" v-if="travelList.length === 1" class="btn-add btn-add2 box box-ver box-ac box-jc">
            <div class="icon icon-index-add2"></div>
            <div >申请出差，添加行程</div>
          </div>
        </div>
      </div>
      <div class="btn-list box box-ac">
        <div @click="addXinCen()" class="box-f1 btn box box-ac box-jc">我要出差</div>
        <div @click="caiBao()" class="box-f1 btn box box-ac box-jc">出差报销</div>
      </div>
    </div>
    <div class="overdraft model">
      <div class="box box-ac head">
        <div class="left"></div>
        <div class="text">我要借/还款</div>
      </div>
      <div v-if="allAmountBanlance > 0" class="box box-ac tips">
        <div class="icon icon-index-jiekuan"></div>
        <div class="text">
          <!-- 还有{{allAmountBanlance}}元借款未还清，请记得尽快还款哟~ -->
          还有{{allAmountBanlance}}元借款未还清，请记得尽快<span @click="huankuan()" class="tc-main">还款</span>哟~
        </div>
      </div>
      <div v-if="allAmountBanlance === 0" class="box box-ac tips">
        <div class="icon icon-index-huankuan"></div>
        <div class="text">
          <!-- 暂无欠款，表现棒棒哒~ -->
          暂无欠款，表现棒棒哒，可以去<span @click="jiekuan()" class="tc-main">借款</span>哟~
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import { mapState } from 'vuex'
import { formatDate } from '@/assets/js/filters'
import { countDate, filterList, initEvectionItem, getAddDate } from '@/assets/js/common'
import { getEvectionReqBills } from '@/assets/js/api'
const typeConf = {
  tel: {
    icon: require('../assets/images/icon-budget-tel.png'),
    name: '通讯费',
    color: '#87d459'
  },
  // 车辆费
  car: {
    icon: require('../assets/images/icon-budget-car.png'),
    name: '车辆费',
    color: '#1e8eee'
  },
  // 交通费
  bus: {
    icon: require('../assets/images/icon-budget-bus.png'),
    name: '交通费',
    color: '#7ac2f1'
  },
  other: {
    icon: require('../assets/images/icon-budget-other.png'),
    name: '其他',
    color: '#f9c214'
  }
}

export default {
  name: 'index',
  data () {
    return {
      budget: {
        available: null,
        decAvailable: null,
        list: []
      },
      travelEmpty: require('../assets/images/travel-empty.png'),
      travelList: [],
      // 未归还金额
      allAmountBanlance: null
    }
  },
  computed: mapState(['userNum', 'userInfo', 'getBudgetDo']),
  watch: {
    getBudgetDo () {
      this.formatChartData(this.getBudgetDo)
    }
  },
  mounted () {
    this.$store.commit('getBudgetDo')
    this.getEvectionReqBills()
    this.getDailyLoanBills()
  },
  methods: {
    selectInvoice (item) {
      // console.log(item)
      if (item.value === 0) {
        this.$tools.openToast({
          msg: '无可用额度',
          duration: 2000
        })
        return
      }
      if (item.expenseType !== 'other') {
        // 常用费用类型
        this.$store.commit('resetBizAccountBill')
        this.$store.commit('bizAccountBill', {
          isComExpense: true,
          expenseNum: item.expenseNum,
          expenseName: item.name,
          expenseId: item.expenseId,
          expenseType: item.expenseType,
          cause: item.name
        })
        this.$router.push({
          path: '/invoice',
          query: {
            JM: 'FB'
          }
        })
      } else {
        this.$router.push('/expenseType')
      }
    },
    formatDate (date) {
      if (!date) return ''
      let arr = date.split('-')
      return `${arr[1]}月${arr[2]}日`
    },
    // 获取我的借款单（未还款金额）
    getDailyLoanBills () {
      this.$http({
        url: this.$config.api.host,
        data: {
          method: 'getDailyLoanBills',
          userNum: this.userNum,
          state: `[45,70]`,
          bizDate: JSON.stringify(['2010-01-01', '2030-01-01'])
        }
      }).then(res => {
        if (res.code === 200) {
          let allAmountBanlance = 0
          res.t.forEach(item => {
            allAmountBanlance += (+item.amountBalance)
          })
          this.allAmountBanlance = allAmountBanlance
        }
      })
    },
    xinCenList () {
      this.$router.push({
        path: '/xinCenList'
      })
    },
    // 添加行程
    addXinCen () {
      let item1 = initEvectionItem()
      // console.log(item1)
      let item2 = JSON.parse(JSON.stringify(item1))
      item2.from = item1.to
      item2.to = ''
      item2.startTime = item1.endTime
      item2.endTime = ''
      this.$store.commit('resetBizAccountBill')
      this.$store.commit('bizAccountBill', {
        entrys: [item1, item2],
        eveNum: '',
        cause: ''
      })
      this.$router.push({
        path: '/xinCenStep1',
        query: {
          type: 'new'
        }
      })
    },
    caiBao () {
      this.$store.commit('resetBizAccountBill')
      this.$store.commit('bizAccountBill', {
        marchInfos: []
      })
      this.$router.push({
        path: '/caiBaoStep1',
        query: {
          type: 'new'
        }
      })
    },
    // 新建借款单
    jiekuan () {
      this.$store.commit('resetBizAccountBill')
      let loanDate = formatDate(new Date(), 'yyyy-MM-dd')
      this.$store.commit('bizAccountBill', {
        loanDate,
        returnDate: getAddDate(loanDate, 30),
        expenseName: '请选择',
        dailyLoanNum: '',
        relateBillNumber: '',
        companyName: this.userInfo.companyName,
        companyNum: this.userInfo.companyNum,
        costCenterName: this.userInfo.depName,
        costDeptNum: this.userInfo.depNum
      })
      this.$router.push('/jiekuanStep1')
    },
    huankuan () {
      this.$store.commit('resetBizAccountBill')
      this.$router.push('/huankuanStep1')
    },
    initTravelList (list) {
      let travelList = []
      let today = formatDate(new Date(), 'yyyy-MM-dd')
      list.forEach(item => {
        if (item.startDate && (+item.startDate.replace(/-/g, '')) > (+today.replace(/-/g, ''))) {
          travelList.push(item)
        }
      })
      // console.log('list>>>', list)
      travelList.sort((a, b) => {
        return (+a.startDate.replace(/-/g, '')) > (+b.startDate.replace(/-/g, ''))
      })
      this.travelList = travelList.filter(item => {
        return (item.state && (+item.state) === 60 && countDate(today, item.createtime.split(' ')[0]) < 90)
      }).map(item => {
        let travelPersonShow = item.travelPerson.join(`<span class="tc-999">&nbsp;|&nbsp;</span>`)
        item.travelPersonShow = travelPersonShow
        return item
      })
    },
    // 获取我的行程
    getEvectionReqBills () {
      if (localStorage.getItem('getEvectionReqBills')) {
        this.initTravelList(JSON.parse(localStorage.getItem('getEvectionReqBills')))
      }
      getEvectionReqBills({
        userNum: this.userNum,
        startDay: JSON.stringify(['2017-01-01', '2022-01-01'])
      }, list => {
        this.initTravelList(list)
        localStorage.setItem('getEvectionReqBills', JSON.stringify(list))
      })
    },
    formatChartData (list) {
      let available = 0
      let decAvailable = 0
      let colorArr = ['#d7d7d7']
      let chartData = [{
        name: '未使用'
      }]

      let otherObj = {
        name: '其他',
        icon: typeConf['other'].icon,
        color: typeConf['other'].color,
        expenseType: 'other',
        value: 0
      }

      this.budget.list = []
      list.forEach(item => {
        available += (+item.available)
        decAvailable += (+item.decAvailable)
        let { name, icon, color } = typeConf[item.expenseType]
        let { expenseNum, expenseType, expenseId } = item
        if (item.expenseType === 'other') {
          otherObj.value += (+item.decAvailable)
        } else {
          let data = {
            name,
            icon,
            color,
            expenseNum,
            expenseType,
            expenseId,
            value: +item.decAvailable
          }
          colorArr.push(color)
          chartData.push(data)
          this.budget.list.push(data)
        }
      })

      if (otherObj.value > 0) {
        colorArr.push(otherObj.color)
        chartData.push(otherObj)
        this.budget.list.push(otherObj)
      }

      chartData[0].value = available
      this.budget.decAvailable = Math.floor(decAvailable) // decAvailable.toFixed(2)
      this.budget.available = Math.round(100 * (available / (decAvailable + available))) + '%'

      let options = {
        series: [
          {
            type: 'pie',
            radius: ['70%', '90%'],
            // avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              }
            },
            color: colorArr,
            data: chartData
          }
        ]
      }

      const myChart = echarts.init(this.$refs.chart)
      myChart.setOption(options)
    },
    seeBudgetDetail () {
      window.open(this.$config.url.myquota)
      // location.href = this.$config.url.myquota
    },
    travelbilldetail (item) {
      localStorage.setItem('billname', '出差申请单')
      localStorage.setItem('cause', item.cause)
      localStorage.setItem('state', item.state)
      localStorage.setItem('money', item.amount)
      window.open(`${this.$config.url.travelbilldetail}?billNum=${item.number}`)
      // location.href = `${this.$config.url.travelbilldetail}?billNum=${item.number}`
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/config';
@import '../assets/css/mixins';
.chart-container{
  width:100%;
  height:4rem;
  padding-top:.4rem;
  padding-bottom:.4rem;
  @include bg-image('../assets/images/bg-index-chart');
  .chart-text{
    position: absolute;
    z-index:1;
    width:3rem;
    height:3rem;
    top:.9rem;
    left:50%;
    margin-left:-1.5rem;
    color:#FFF;
    .text-small{
      font-size:.25rem;
    }
    .text-big{
     font-size:.46rem;
     padding: .25rem 0;
    }
  }
  .chart{
    width:4rem;
    height:4rem;
    margin:0 auto;
  }
}
.budget-list{
  padding:0;
  background-color:rgba(0,0,0,0);
  margin-top:-1px;
  .item{
    color:#FFF;
    height:1.5rem;
    width:100%;
    .icon-budget-small{
      height:.45rem;
    }
    .icon-budget-big{
      margin-right:.2rem;
      height:.65rem;
    }
    .text{
      padding-left:.1rem;
      font-size:.26rem;
    }
    .value{
      padding-top:.06rem;
      font-size:.36rem;
    }
  }
}

.model{
  padding: 0 .18rem;
  background-color:#FFF;
  margin-top:.25rem;
  .head{
    padding:.25rem 0;
    color:#333;
    font-size:.3rem;
    .left{
      width:.1rem;
      height:.3rem;
      line-height:.3rem;
      background-color:$themeColor;
      margin-right:.1rem;
    }
  }
}

.travel-empty{
  font-size:.2rem;
  color:#999;
  padding-bottom:.2rem;
  .icon-travel-empty{
    width:1.98rem;
    margin-bottom:.2rem;
  }
}

.bill-item{
  width:2.8rem;
  height:2.02rem;
  border-radius:.2rem;
  overflow: hidden;
  background-color:#f8f8f8;
  margin-right:.2rem;
  color:#888;
  .time{
    background-color:#c8def8;
    height:.5rem;
    font-size:.18rem;
    color:#333;
    line-height:.5rem;
  }
  .area{
    padding: 0 .2rem;
    margin-top:.2rem;
    color:#333;
    .icon-index-arrow{
      width:.37rem;
      height:.21rem;
      margin:0 .1rem;
      @include bg-image('../assets/images/icon-index-arrow');
    }
    .ell{
      text-align: center;
      height:.222rem;
      font-size:.22rem;
    }
  }
  .cause{
    padding:.2rem;
    padding-bottom: 0;
    font-size:.18rem;
  }
  .user{
    // padding-top:.2rem;
    padding:.2rem;
    font-size:.22rem;
    // .item{
    //   padding: 0 .08rem;
    //   height:.34rem;
    //   border-radius:.06rem;
    //   font-size:.18rem;
    //   border:1px solid $borderColor;
    //   margin-left:.2rem;
    // }
  }
}

.btn-add{
  border:1px solid $borderColor;
  height:2.02rem;
  width:1.28rem;
  border-radius:.2rem;
  color:#999;
  font-size:.14rem;
  &.btn-add2{
    width:2.8rem;
  }
}

.travel-list{
  width:100%;
  padding-bottom:.25rem;
  &.type1{
    padding-left:.5rem;
    padding-right:.5rem;
    .btn-add2{
      width:2.78rem;
      margin-left:.4rem;
    }
  }
}

.icon-index-add{
  width:.32rem;
  height:.32rem;
  @include bg-image('../assets/images/icon-index-add');
}
.icon-index-add2{
  width:.66rem;
  height:.84rem;
  margin-bottom:.2rem;
  @include bg-image('../assets/images/icon-index-add2');
}
.btn-list{
  border-top:1px solid $borderColor;
  height:1rem;
  .btn{
    height:.8rem;
    font-size:.24rem;
    color:#666;
    &:nth-of-type(1){
      border-right:1px solid $borderColor;
    }
  }
}

.icon-index-jiekuan{
  width:.38rem;
  height:.3rem;
  @include bg-image('../assets/images/icon-index-jiekuan')
}

.icon-index-huankuan{
  width:.37rem;
  height:.37rem;
  @include bg-image('../assets/images/icon-index-huankuan')
}

.overdraft{
  color:#888;
  .tips {
    padding-top:.2rem;
    padding-bottom:.45rem;
    padding-left:.3rem;
    font-size:.26rem;
    .icon{
      margin-right:.2rem;
    }
  }
}
</style>
